package controller

import (
    "net/http"
    "strconv"

    "github.com/gin-gonic/gin"
    "generator-tool/models"
    "generator-tool/service"
)

type ShGoodController struct {
    Service *service.ShGoodService
}

func NewShGoodController(service *service.ShGoodService) *ShGoodController {
    return &ShGoodController{Service: service}
}

func (ctl *ShGoodController) Create(c *gin.Context) {
    var ShGood models.ShGood
    if err := c.ShouldBindJSON(&ShGood); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    if err := ctl.Service.CreateShGood(&ShGood); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusCreated, gin.H{"data": ShGood})
}

func (ctl *ShGoodController) GetAll(c *gin.Context) {
    ShGoods, err := ctl.Service.GetAllShGoods()
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }
    c.JSON(http.StatusOK, gin.H{"data": ShGoods})
}

func (ctl *ShGoodController) GetByID(c *gin.Context) {
    id, err := strconv.ParseUint(c.Param("id"), 10, 32)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
        return
    }

    ShGood, err := ctl.Service.GetShGoodByID(uint(id))
    if err != nil {
        c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, gin.H{"data": ShGood})
}

func (ctl *ShGoodController) Update(c *gin.Context) {
    id, err := strconv.ParseUint(c.Param("id"), 10, 32)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
        return
    }

    var ShGood models.ShGood
    if err := c.ShouldBindJSON(&ShGood); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    if err := ctl.Service.UpdateShGood(uint(id), &ShGood); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, gin.H{"message": "updated successfully"})
}

func (ctl *ShGoodController) Delete(c *gin.Context) {
    id, err := strconv.ParseUint(c.Param("id"), 10, 32)
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "invalid id"})
        return
    }

    if err := ctl.Service.DeleteShGood(uint(id)); err != nil {
        c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, gin.H{"message": "deleted successfully"})
}